<template>
  <div style="height: 100%">
    <vxe-grid
      ref="gridRef"
      v-bind="gridOptions"
      @toolbar-button-click="toolbarButtonClickEvent"
    >
      <template #active="{ row }">
        <vxe-button
          mode="text"
          v-show="row.createTime != undefined"
          status="primary"
          content="删除"
          icon="vxe-icon-edit"
          @click="deleteData(row)"
        ></vxe-button>

        <vxe-button
          v-show="row.createTime == undefined"
          mode="text"
          status="error"
          @click="removeRow(row)"
          >删除</vxe-button
        >
      </template>
    </vxe-grid>
  </div>
</template>

<script>
import { VxeUI } from "vxe-pc-ui";
import XEUtils, { first } from "xe-utils";
import { getWoRawSubByPage, delWoRawSub } from "@/api/product/woRawSub";

import {
  addWoRawRel,
  startWoRaw,
  insertWoRawRel,
  endWoRaw,
  insertWoRawRels,
} from "@/api/product/woRawRel";
export default {
  name: "workSub",
  props: {
    formData: {
      type: Object,
      default: () => {
        return {
          workNo: "",
          maxCount: 0,

          // fixedPagination: true
        };
      },
    },
    woType: {
      type: String,
      default: () => {
        return "";
      },
    },
    woRawSub: {
      type: Object,
      default: () => {
        return {
          wo: "",
          workNo: "",
          id: 0,
          // fixedPagination: true
        };
      },
    },
    // reflushAction: {

    // }
  },
  watch: {
    woRawSub: {
      immediate: true,
      deep: true,
      handler(val, oldVal) {
        this.localWoRawSub = val;
        if (val.wo != "" && val.wo != undefined) {
          console.log(this.localWoRawSub, "===>代码修改提交===>");
          setTimeout(() => {
            this.$refs.gridRef.commitProxy("reload");
          }, 100);
        }

        // this.initTableColumn(val);
      },
    },
  },
  data() {
    const gridOptions = {
      sortConfig: {
        remote: true,
      },
      height: "100%",
      editConfig: {
        trigger: "click",
        mode: "cell",
        showStatus: true,
      },
      loading: false,
      stripe: true,
      showOverflow: true,
      showFooter: true,

      columnConfig: {
        resizable: true,
        drag: true,
      },
      columnDragConfig: {
        trigger: "cell",
        showIcon: false,
        showGuidesStatus: true,
      },
      rowConfig: {
        isHover: true,
      },
      resizableConfig: {
        isDblclickAutoWidth: true,
      },
      pagerConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
      },
      formConfig: {
        data: {
          name: "",
          role: "",
          sex: "",
          num: "",
          address: "",
        },
        items: [
          {
            field: "name",
            title: "名称",
            span: 8,

            itemRender: { name: "VxeInput", props: { clearable: true } },
          },

          {
            field: "createTime",
            title: "时间",
            span: 8,

            itemRender: {
              name: "VxeDatePicker",
              props: {
                multiple: true,
              },
            },
          },

          {
            collapseNode: true,
            align: "right",
            span: 8,
            itemRender: {
              name: "VxeButtonGroup",
              options: [
                { type: "submit", content: "搜索", status: "primary" },
                { type: "reset", content: "重置" },
              ],
            },
          },
        ],
      },
      toolbarConfig: {
        custom: true,
        buttons: [
          { name: "新增", code: "myAdd", status: "primary" },
          { name: "保存", code: "mySave", status: "error" },

          // { name: "保存", code: "mySave", status: "success" },
        ],
      },

      columns: [
        { type: "checkbox", width: 60 },
        { field: "seq", type: "seq", width: 70 },

        { field: "wo", title: "工单号", sortable: true, width: 180 },
        { field: "serialNo", title: "序列号", sortable: true, width: 180 },
        { field: "materialCode", title: "物料号", sortable: true, width: 180 },
        {
          field: "length",
          title: "数量",
          sortable: true,
          width: 180,
          editRender: { name: "VxeNumberInput", props: { type: "float" } },
        },
        // {
        //   field: "rawType",
        //   title: "类型",
        //   sortable: true,
        //   width: 180,
        // },
        { field: "createTime", title: "创建时间", width: 180 },
        {
          field: "active",
          title: "操作",
          fixed: "right",
          width: 200,
          slots: { default: "active" },
        },
      ],
      scrollX: {
        gt: 0,
        enabled: true,
      },
      scrollY: {
        gt: 0,
        enabled: true,
      },
      proxyConfig: {
        // props: {
        //   result: 'result', // 配置响应结果列表字段
        //   total: 'page.total' // 配置响应结果总页数字段
        // },

        sort: true,
        form: true,
        ajax: {
          query: async ({ page, sorts, form }) => {
            console.log(page, sorts, form, "----");

            // 默认接收 Promise<{ result: [], page: { total: 100 } }>
            let result = await getWoRawSubByPage({
              ...page,
              wo: this.formData.workNo,
            });
            this.pagetotal = result.data.total;
            return {
              result: result.data.records,
              page: {
                total: result.data.total,
              },
            };
          },
        },
      },
    };
    return {
      gridOptions,
      pagetotal: 0,
      localWoRawSub: this.woRawSub,
      localFormData: this.formData,
      maxCount: this.formData.maxCount,
      // woType: this.woType,
    };
  },
  methods: {
    async toolbarButtonClickEvent(params) {
      if (params.code == "myAdd") {
        const $grid = this.$refs.gridRef;
        if (
          this.localFormData.workNo == "" ||
          this.localFormData.workNo == undefined
        ) {
          VxeUI.modal.message({
            content: "请先输入工单信息",
            status: "error",
          });
        } else {
          if ($grid) {
            this.maxCount =
              this.pagetotal + $grid.getInsertRecords().length + 1;
            const record = {
              rawCode: ``,
              wo: this.localFormData.workNo,
              qty: 1,
              status: "未消耗",
              active: "",
              materialCode: this.localFormData.materialCode,
              serialNo:
                this.localFormData.workNo +
                "-" +
                this.maxCount.toString().padStart(2, "0"),
            };
            const { row: newRow } = await $grid.insert(record);
            // 激活不自动聚焦
            $grid.setEditRow(newRow);

            // 激活并自动聚焦
            // $grid.setEditRow(newRow, 'name')
            // 激活并自动聚焦
            // $grid.setEditCell(newRow, 'name')
          }
        }
        // this.showPopup = true;
      } else if (params.code == "mySave") {
        // const $grid = this.$refs.gridRef;
        // if ($grid) {
        //   const selectRecords = $grid.getCheckboxRecords();
        //   if (selectRecords.length <= 0) {
        //     VxeUI.modal.message({ content: `请先选择数据`, status: "warning" });
        //   }
        // }
        const $grid = this.$refs.gridRef;
        console.log($grid, "-----$grid---");
        if ($grid) {
          const insertRecords = $grid.getInsertRecords();
          const result = await insertWoRawRels(insertRecords);
          $grid.commitProxy("reload");
          // VxeUI.modal.alert(`新增：${insertRecords.length} 行`);
        }
        console.log("===>保存===>");
      }
      console.log(params.code);
    },
    async searchRawData(row) {
      console.log("==row==>", row);
      // let result = await getWoRawByPage({
      //   currentPage: 1,
      //   pageSize: 100,
      //   wo: row.wo,
      //   subId: row.id,
      // });
      this.woRawSub = row;
      // this.tableData2 = result.data.records;
      this.activeTab = "2";
      const $grid2 = this.$refs.gridRef2.commitProxy("reload");
      console.log(this.tableData);
    },
    async recordDefective(row) {
      this.showPopup3 = true;
      /**
       * 等会
       */
      this.modalOptions3.title = "子卷的缺陷信息";
      this.formOptions3.data.woRawSubId = row.id;
    },
    async searchFaultData(row) {
      console.log("==row==>", row);
      // let result = await getWoRawByPage({
      //   currentPage: 1,
      //   pageSize: 100,
      //   wo: row.wo,
      //   subId: row.id,
      // });
      this.woRawSub = row;
      // this.tableData2 = result.data.records;
      this.activeTab = "3";
      const $grid2 = this.$refs.gridRef3.commitProxy("reload");
      console.log(this.tableData);
    },
    removeRow(row) {
      const $grid = this.$refs.gridRef;
      if ($grid) {
        $grid.remove(row);
        VxeUI.modal.message({
          content: "数据已删除",
          status: "success",
        });
      }
    },
    async deleteData(row) {
      try {
        await delWoRawSub(row);
      } catch (error) {
      } finally {
        this.$refs.gridRef2.commitProxy("reload");
      }
    },
    reflushTable() {
      this.$refs.gridRef.commitProxy("reload");
    },
  },
};
</script>
